<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>
        通过点击绘制顶点
    </title>
</head>

<body onload="main()">
<canvas id="example" width="400" height="400" style="border: 1px solid red;"> canves</canvas>
<script src="../js/cuon-utils.js"></script>
<script src="../js/webgl-debug.js"></script>
<script src="../js/webgl-utils.js"></script>
<script>
    // 顶点着色器
    // 'attribute float a_PointSize;' +
    var VSHADER_SOURCE = 'attribute vec4 a_Position;\n' +
        ' void main() {\n' +
        ' gl_Position = a_Position;\n' + // 设置坐标
        ' gl_PointSize = 10.0;\n' +// 设置尺寸
        '}\n';

    // 片元着色器
    var FSHADER_SOURCE = 'void main() {\n' +
        ' gl_FragColor = vec4(1.0,0.0,0.0,1.0);\n' + // 设置颜色
        '}\n';

    function main() {

        var canves = document.getElementById("example");

        var gl = getWebGLContext(canves);

        // 初始化着色器
        if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
            console.error("着色器加载错误")
            return;
        }

        // 获取attribute变量存储的位置
        var a_Position = gl.getAttribLocation(gl.program, 'a_Position');

        if (a_Position < 0) {
            console.error("参数错误")
            return;
        }

        // 将顶点变量传给attribute变量
        gl.vertexAttrib1f(a_Position, 0.0);

        gl.clearColor(0.0, 1.0, 0.0, 1.0);
        gl.clear(gl.COLOR_BUFFER_BIT);

        gl.drawArrays(gl.POINTS, 0, 1);

        canves.onmousedown = function (ev) {
            click(ev, gl, canves, a_Position);
        }
        // canves.onmousemove = function (ev) {
        //     click(ev, gl, canves, a_Position);
        // }
        // canves.onmouseover = function (ev) {
        //     click(ev, gl, canves, a_Position);
        // }
        // canves.onmouseenter = function (ev) {
        //     click(ev, gl, canves, a_Position);
        // }
        // canves.onmouseleave = function (ev) {
        //     click(ev, gl, canves, a_Position);
        // }
        // canves.onmouseup = function (ev) {
        //     click(ev, gl, canves, a_Position);
        // }
        // canves.onmouseout = function (ev) {
        //     click(ev, gl, canves, a_Position);
        // }

    }

    var g_points = [];

    function click(ev, gl, canvas, a_Position) {
        var x = ev.clientX;
        var y = ev.clientY;

        var rect = ev.target.getBoundingClientRect();

        x = ((x - rect.left) - canvas.height / 2) / (canvas.height / 2);
        y = (canvas.width / 2 - (y - rect.top)) / (canvas.width / 2)

        g_points.push(x)
        g_points.push(y)

        gl.clear(gl.COLOR_BUFFER_BIT);

        var len = g_points.length;
        for (var i = 0; i < len; i += 2) {
            gl.vertexAttrib3f(a_Position, g_points[i], g_points[i + 1], 0.0)
            gl.drawArrays(gl.POINTS, 0, 1)
        }
    }

</script>
</body>

</html>